//
//  OuathAuthViewController.m
//  OuathAuth
//
//  Created by JayaKarthigayan on 23/06/10.
//  Copyright Apple Inc 2010. All rights reserved.
//

#import "OuathAuthViewController.h"
#import "SA_OAuthTwitterEngine.h"
#import "Reachability.h"
#import "AppDelegate_iPhone.h"

static	NSString *mUserName;
int TwiloginTag=0;

@implementation OuathAuthViewController
@synthesize twitMessage,sharedLink,appTwitterAccount,mMessageDialog;
@synthesize sa_OAuthTwitterController;
//@synthesize isAuthentc;
@synthesize _engine;
static BOOL isAuthentc=FALSE;
 NSString *tempUserData;
@synthesize delegate;

@synthesize mCancelData,mPostData;
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
}

- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

//=============================================================================================================================
#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
	mUserName=username;
	
	NSUserDefaults	*defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject: username forKey: @"twitter_screenName"];
	[defaults synchronize];
	isAuthentc=TRUE;
	//if (self.delegate && [self.delegate respondsToSelector:@selector(didAuthenticatedWithUserName:)]) 
		[self.delegate didAuthenticatedWithUserName:username];

	
	
	[sa_OAuthTwitterController.view removeFromSuperview];
	isAuthentc=TRUE;
	
	[self createAlert];
	
	
}

- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
	[sa_OAuthTwitterController.view removeFromSuperview];
	[_engine clearAccessToken];

	
	NSUserDefaults	*defaults2 = [NSUserDefaults standardUserDefaults];
	[defaults2 setObject: @"" forKey: @"twitter_screenName"];
	[defaults2 synchronize];
	if(tempUserData)
	{
		[tempUserData release];
		tempUserData=nil;
		
	}
	
	[self.delegate didAuthenticatedWithUserName:@""];
	
	NSLog(@"Authentication Failed!");
}

- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
	DEBUG_LOG(@"Authentication Canceled.");
	[self.delegate didAuthenticatedCancel];	
	if(tempUserData)
	{
		NSUserDefaults	*defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject:tempUserData forKey: @"authData"];
		[defaults synchronize];
	}
	[sa_OAuthTwitterController.view removeFromSuperview];
		
}

//=============================================================================================================================
#pragma mark TwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
	UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Posted!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
	[aler show];
	[aler release];
	DEBUG_LOG(@"Request %@ succeeded", requestIdentifier);
}

- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
	if ([error code] == 403) {
		UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Duplicated tweet" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
		[aler show];
		[aler release];
	} else {
		UIAlertView* aler = [[UIAlertView alloc] initWithTitle:@"Twitter" message:@"Tweet Failed!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
		[aler show];
		[aler release];
	}	
	DEBUG_LOG(@"Request %@ failed with error: %d", requestIdentifier, [error code]);
}

//=============================================================================================================================
#pragma mark ViewController Stuff
- (void)dealloc {
	[_engine release];
	[sa_OAuthTwitterController release];

    [super dealloc];
}

- (void) viewDidAppear: (BOOL)animated {
		
}

-(void)createAlert
{
	if([twitMessage isEqualToString:@""])
		return;
	
	isTwitterOpened=YES;
	mTransparentImg = [[UIView alloc]init];
	mTransparentImg.backgroundColor=[UIColor clearColor];
	mMessageDialog = [[UIView alloc] init];
	
#if __isIpadDevice ==0

	UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

	[mTransparentImg setBackgroundColor:[UIColor blackColor]];
	if (orientation ==UIInterfaceOrientationLandscapeLeft || orientation ==UIInterfaceOrientationLandscapeRight)
	{
		mMessageDialog.frame=CGRectMake(20, 0, 275, 155);
		mTransparentImg.frame=CGRectMake(0, 0, 480, 320);		
	}
	else {
		mMessageDialog.frame=CGRectMake(22.5, 60, 275, 155);
		mTransparentImg.frame=CGRectMake(0, 0, 320, 480);
	}
	
#else 	#if __isIpadDevice ==1

	mTransparentImg.frame=CGRectMake(0, 0, 768, 1024);
	mMessageDialog.frame=CGRectMake(110, 0, 275, 155);
	mMessageDialog.center=self.view.center;

#endif	//mTransparentImg.opaque=YES;
	[mTransparentImg setOpaque:YES];

	[prnttViewController.view addSubview:mTransparentImg];
	
	[prnttViewController.view addSubview:mMessageDialog];
	[mTransparentImg release];
	
	[mTransparentImg setBackgroundColor:[UIColor blackColor]];
	mTransparentImg.alpha=0.3;

	UIImageView *bgView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"twitter_post_bg.png"]];
	
	bgView.frame=CGRectMake(0, 0 , 275, 155);
	[bgView setContentMode:UIViewContentModeScaleToFill];
	[mMessageDialog addSubview:bgView];
	[bgView release];
	mMessageDialog.backgroundColor=[UIColor whiteColor];
	//// creating a textview with background image and adding it to custom view///
	
	UIImageView* bg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fb_message_bg.png"]];
	txtMessage = [[UITextView alloc] initWithFrame:CGRectMake(15, 31, 240, 60)];
	[txtMessage setEditable:YES];
	
	UIImageView *textboxBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"textbox_background.png"]];
	[textboxBg setBackgroundColor:[UIColor clearColor]];
	[mMessageDialog addSubview:textboxBg];
	textboxBg.frame = txtMessage.frame;
	[textboxBg release];
	
	
	[txtMessage setBackgroundColor:[UIColor whiteColor]];
	txtMessage.delegate=self;
	bg.frame = txtMessage.frame;
	

	[bg setContentMode:UIViewContentModeScaleToFill];
	txtMessage.text=twitMessage;
	[mMessageDialog addSubview:bg];
	[bg release];
	[mMessageDialog addSubview:txtMessage];
	txtMessage.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
	[txtMessage setTextColor:[UIColor blackColor]];
	[mMessageDialog bringSubviewToFront:txtMessage];
	txtMessage.editable = YES;

	//// creating a noofchar left label///////
	
	lblCharLeft = [[UILabel alloc] initWithFrame:CGRectMake(0, 6, 250, 20)];
	lblCharLeft.font = [UIFont boldSystemFontOfSize:14.0f];

	lblCharLeft.textAlignment = UITextAlignmentRight;
	lblCharLeft.textColor = [UIColor whiteColor];
	lblCharLeft.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
	[mMessageDialog addSubview:lblCharLeft];
	[lblCharLeft release];
	
	int left = maxCharLength - ([sharedLink length]+[appTwitterAccount length] + [txtMessage.text length]+1);
	lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
	
	
	////// creating Enter text message label
	
	UILabel *lb1=[[UILabel alloc]initWithFrame:CGRectMake(15, 3, 250, 30)];
	lb1.textAlignment = UITextAlignmentCenter;
	lb1.backgroundColor =[UIColor colorWithRed:0 green:0 blue:0 alpha:0]; 
	lb1.textColor = [UIColor whiteColor];
	lb1.text=@"Tweet this post";
	lb1.font = [UIFont boldSystemFontOfSize:20.0f];
	lb1.numberOfLines=2;
	[mMessageDialog addSubview:lb1];
	[lb1 release];
	
	
	///creating buttons for posting data and cancelling posting
	
	mPostData = [UIButton buttonWithType:UIButtonTypeCustom];
		[mPostData addTarget:self 
				   action:@selector(postDataButtonPressed)
		  forControlEvents:UIControlEventTouchUpInside];
	
	[mPostData setBackgroundImage :[UIImage imageNamed:@"twitter_post_button_nonhighlighted.png"] forState:UIControlStateNormal];
	[mPostData setBackgroundImage :[UIImage imageNamed:@"twitter_post_button_highlighted.png"] forState:UIControlStateHighlighted];

		[mPostData setTitle:@"Show View" forState:UIControlStateNormal];
	mPostData.frame=CGRectMake(10, 100, 128, 40);
	[mPostData setTitle:@"Post" forState:UIControlStateNormal];
	[mPostData setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[mMessageDialog addSubview:mPostData];
	
	//  cancel button ///
	
	mCancelData = [UIButton buttonWithType:UIButtonTypeCustom];
		[mCancelData addTarget:self 
				   action:@selector(cancelButtonPressed)
		 forControlEvents:UIControlEventTouchUpInside];
	
	[mCancelData setBackgroundImage :[UIImage imageNamed:@"twitter_post_button_nonhighlighted.png"] forState:UIControlStateNormal];
	[mCancelData setBackgroundImage :[UIImage imageNamed:@"twitter_post_button_highlighted.png"] forState:UIControlStateHighlighted];
	
	[mCancelData setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	mCancelData.frame=CGRectMake(144, 100, 120, 40);
	[mCancelData setTitle:@"Cancel" forState:UIControlStateNormal];
	[mMessageDialog addSubview:mCancelData];
	
	
	UIImageView* logo1 = [[UIImageView alloc] initWithFrame:CGRectMake(8, 3, 42, 42)];
	logo1.image = [UIImage imageNamed:@"twitter-logo-twit.png"];
	[mMessageDialog addSubview:logo1];
	[logo1 release];
	[mMessageDialog setBackgroundColor:[UIColor clearColor]];
	
}

-(void)postDataButtonPressed
{
	isTwitterOpened=NO;

	NSArray *arr=[mMessageDialog subviews];
	for (int i=0; i<[arr count]; i++) {
		
		[[arr objectAtIndex:i]removeFromSuperview];
	}
	[mTransparentImg removeFromSuperview];

	[_engine sendUpdate:[NSString stringWithFormat:@"%@  %@ %@",txtMessage.text,sharedLink,appTwitterAccount]];
	[mMessageDialog removeFromSuperview];

}
/// button action to cancel posting of data

-(void)cancelButtonPressed
{
	isTwitterOpened=NO;
	NSArray *arr=[mMessageDialog subviews];
	for (int i=0; i<[arr count]; i++) {
		
		[[arr objectAtIndex:i]removeFromSuperview];
	}
	[mTransparentImg removeFromSuperview];
	[mMessageDialog removeFromSuperview];	
}


-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	isTwitterOpened=NO;
	if([[alertView buttonTitleAtIndex:buttonIndex] compare:@"Send"] == NSOrderedSame){
		[_engine sendUpdate:[NSString stringWithFormat:@"%@  %@ %@",txtMessage.text,sharedLink,appTwitterAccount]];
		

	}	
	
}

-(NSString*)returnUserName
{
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"twitter_screenName"];
}

- (void)logoutOfTwitter
{
	[_engine clearAccessToken];
	isAuthentc = FALSE;
	[_engine release];
	_engine = nil;
	
    //[[NSUserDefaults standardUserDefaults] setObject:@"" forKey: @"twitter_screenName"];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey: @"authData"];
	//[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"twitter_screenName"];
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"authData"];
	
}

-(void)Login :(id)parent
{
	_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
	_engine.consumerKey = kOAuthConsumerKey;
	_engine.consumerSecret = kOAuthConsumerSecret;
	UIViewController		*controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
	UIApplication *app = [UIApplication sharedApplication];
	UIViewController *prnttViewControllerLocal=(UIViewController *)parent;
	
	
	if(controller)
	{
		if(sa_OAuthTwitterController)
		{ 
			[sa_OAuthTwitterController release];
			sa_OAuthTwitterController=nil;
		}
		if (isAuthentc==FALSE) {
			if(sa_OAuthTwitterController==nil)
				sa_OAuthTwitterController = [[SA_OAuthTwitterController  alloc] initWithEngine:_engine andOrientation:[app statusBarOrientation]];
			[SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
			sa_OAuthTwitterController.delegate=self;
		}
		
		CGRect fr=prnttViewControllerLocal.view.frame;;
		fr.origin.x=0;
		fr.origin.y=0;
		sa_OAuthTwitterController.view.frame=fr;
		
		[prnttViewControllerLocal.view addSubview:sa_OAuthTwitterController.view];
		
	}
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{

	alertView.frame = CGRectMake(alertView.frame.origin.x,15,alertView.frame.size.width, alertView.frame.size.height);

}

  
#pragma mark Textview delegates

///////////text view delegate Functions////


- (void)textViewDidChange:(UITextView *)textView
{
	int left = maxCharLength - ([sharedLink length]+[appTwitterAccount length] + [textView.text length]+2);
	lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
	
	
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
	// Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];
		
        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
	if([text length]<=0)
		return YES;
	
	
	int	charLeft = maxCharLength - ([sharedLink length]+[appTwitterAccount length] + [textView.text length]+2);
	if(charLeft<=0)
		return FALSE;
	
	const char* str = [text UTF8String];
	
	int s = str[0];
	if(s!=0)
		if((range.location + range.length) > maxCharLength- [appTwitterAccount length]-[sharedLink length]-1){
			return NO;
		}else{
			int left = maxCharLength - ([sharedLink length]+[appTwitterAccount length] + [textView.text length]+2);
			lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
			return YES;
		}
	
	return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
	return YES;	
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
	//messageDialog.frame = CGRectMake(messageDialog.frame.origin.x,15,messageDialog.frame.size.width, messageDialog.frame.size.height);

	if ([[textView text] isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];
		
        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
	if([[textView text] length] > maxCharLength- [appTwitterAccount length]-[sharedLink length]-1){
		return NO;
	}else{
		int left = maxCharLength - ([sharedLink length]+[appTwitterAccount length] + [textView.text length]+2);
		lblCharLeft.text= [NSString stringWithFormat:@"%d",left];
		return YES;
	}
	return YES;
	
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
	
	DEBUG_LOG(@".");
	[textField becomeFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	[textField resignFirstResponder];
	//[self startUpload];
	return NO;
}

////////////writing new set of code///////////////


- (void) twit:(NSString*)text withLink:(NSString*)link forapp:(NSString *)twitAppname makeTiny:(BOOL)yesOrno :(id)parent
{
	BOOL netConn=[self connectedToNetwork];
	if(!netConn) {
			UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Network Error" message:@"Connection Failed" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
		alt.center=self.view.center;
		[alt show];
		[alt release];
		return;
	}
	
	

	if([text isEqualToString:@""])
	{
		isAuthentc=FALSE;
		if(tempUserData)
		{
			[tempUserData release];
			tempUserData=nil;
			
		}
		NSString *userdata=[[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
		if(userdata)
		tempUserData=[[NSString alloc] initWithString:userdata];
		
		NSUserDefaults	*defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject: @"" forKey: @"authData"];
		[defaults synchronize];
	}
	maxCharLength=139;
	if(link){
		if(yesOrno){
			link = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
			NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://tinyurl.com/api-create.php?url=%@",link]];
			link = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
			
		}
		
		self.sharedLink = link;
	}	
	if(twitAppname)
		self.appTwitterAccount=[NSString stringWithFormat:@" via @%@",twitAppname];
	
	else {
		self.appTwitterAccount=@"";
		self.sharedLink = @"";
	}
	
	self.twitMessage =text;
	
	_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
	_engine.consumerKey = kOAuthConsumerKey;
	_engine.consumerSecret = kOAuthConsumerSecret;
	prnttViewController=(UIViewController *)parent;
	UIViewController		*controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
	UIApplication *app = [UIApplication sharedApplication];

	if(controller!=nil && isAuthentc==FALSE)
	{
		
	if(sa_OAuthTwitterController)
	{ 
		[sa_OAuthTwitterController release];
		sa_OAuthTwitterController=nil;
	}
	if (isAuthentc==FALSE) {
			if(sa_OAuthTwitterController==nil)
	sa_OAuthTwitterController = [[SA_OAuthTwitterController  alloc] initWithEngine:_engine andOrientation:[app statusBarOrientation]];
	sa_OAuthTwitterController.delegate=self;
		[SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
	sa_OAuthTwitterController.delegate=self;
	}		
		CGRect fr=prnttViewController.view.frame;;
		fr.origin.x=0;
		fr.origin.y=0;
		sa_OAuthTwitterController.view.frame=fr;
		
		[prnttViewController.view addSubview:sa_OAuthTwitterController.view];
		[prnttViewController.view  bringSubviewToFront:sa_OAuthTwitterController.view];		
	}	
	else 
	{
		[self createAlert];		
	}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	
	    return YES;
}

-(void)setFrame :(UIInterfaceOrientation)fromInterfaceOrientation 
{
#if __isIpadDevice ==0

	if (fromInterfaceOrientation==UIInterfaceOrientationLandscapeLeft ||  fromInterfaceOrientation==UIInterfaceOrientationLandscapeRight) 
	{
		mTransparentImg.frame=CGRectMake(0, 0, 480, 320);

		mMessageDialog.frame=CGRectMake(110, 0, 275, 155);

	}
	else if (fromInterfaceOrientation==UIInterfaceOrientationPortrait) 
	{
		mTransparentImg.frame=CGRectMake(0, 0, 320, 480);

		mMessageDialog.frame=CGRectMake(22.5, 30, 275, 155);
	}
#endif
}

- (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
	
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
	
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
	
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return 0;
    }	
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
	
    return (isReachable && !needsConnection) ? YES : NO;
}


- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation 
{
	
}

@end
